package com.sakura.滑动窗口;

public class Code904_水果成篮 {
    public int totalFruit(int[] fruits) {
        int res = Integer.MIN_VALUE;
        int l = 0;
        int r = 0;
        int n = fruits.length;
        int[] cnts = new int[n + 10];
        int count = 0;
        while (r < n) {
            cnts[fruits[r]]++;
            if (cnts[fruits[r]] == 1) {
                count++;
            }
            while (count > 2) {
                cnts[fruits[l]]--;
                if (cnts[fruits[l]] == 0) {
                    count--;
                }
                l++;
            }
            res = Math.max(res, r - l + 1);
            r++;
        }
        return res;
    }
}
